from RestAPI.core.ResponseData import DataNode
from RestAPI.core.APIwrapper import RestRequest
##
#The abstract class of requests sent to Amazon Web Services. 
class AWSrequest(RestRequest):
    USE_AMAZON_TIME=False
    def timestamp(self):
        if AWSrequest.USE_AMAZON_TIME:
            return time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
        else:
            return self.timestampFromAWS()
    def timestampFromAWS(self):
        req=RestRequest('cloudfront.amazonaws.com').GET('/date')
        req.send()
        return req.response.getheader('date')
    def authorize(self):
        pass
    def getSignature(self):
        pass
    def getStringToSign(self):
        pass
##
#The abstract class of Configuratoins that can be set for Amazon Web Services.
class AWSConfiguration (object):
    def __init__(self):
        pass
    def headers(self):
        """Returns the request headers need to be added to the AWS request."""
        return {}
    def content(self):
        """Returns the request body need to be sent through AWS requests."""
        return ""

##
#The abstract class of Amazon Web Service. 
#
class AWSservice:
    def setOwner(self):
        """
        Set the owner of the AWS service.
        """
        pass
    def setCredential(self,AuthKey=None,SecretAccessKey=None,securityToken=None):
        """
        Set the credential information of the current bucket.
        """
        self.AuthKey=AuthKey
        self.SecretAccessKey=SecretAccessKey
        self.securityToken=securityToken
        return self
##
#A wrapper for the errors generated from the AWS services. Need be raised with the HTTP response from the AWS as parameter. For example:
# @code
# raise AWSError(req.response)
# @endcode
# This generates error message easier to understand for better debugging.
class AWSError(Exception):
    def __init__(self,response):
        self.httpcode=response.status
        self.httpmsg=response.reason
        self.body=response.read()
        self.headers=""
#        for key in response.getheaders():
#            self.headers+="%s:%s\n" % (key, response.getheader(key))
        if self.body:
            r=DataNode(self.body)
            if len(r['Error']) != 0:
                self.code=r.Code.str()
                self.details=r.Message.str()
            else:
                self.code=""
                self.details=self.body
    def __str__(self):
        return "AWSError.%s: HTTP%s %s!\n%s\n--------------------------------------------\nDetailed xml message:\n%s" % (self.code,self.httpcode,self.httpmsg,self.details,self.body)
